package com.kll.carolinehmibiz.presentation.presenter

import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Message
import com.google.gson.Gson
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.base.utils.L
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.DownloadFileProgress
import com.kll.carolinehmibiz.net.bean.GetAppNewlyVersionResponse
import com.kll.carolinehmibiz.net.bean.GetSystemMenuResponse
import com.kll.carolinehmibiz.presentation.BasePresenter
import com.kll.carolinehmibiz.presentation.listener.MainProtocol

/**
 * ====================================================
 *
 * 主界面presenter
 *
 * Created by Ziliang Cai on 2022/1/2 20:42
 * <a href="mailto:752777456@qq.com">Contact me</a>
 * ====================================================
 */
class MainPresenter(context: Context, mView: MainProtocol.IView): BasePresenter(context), MainProtocol.IPresenter {
    private var mView: MainProtocol.IView? = mView

    private var getAppNewlyVersionIsBusying = false
    private var downloadFileIsBusying = false

    private val WHAT_LOAD_SYSTEM_MENU: Int = 1

    private var mHandler = object : Handler(mContext.mainLooper) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)

            when(msg.what) {
                WHAT_LOAD_SYSTEM_MENU->{
                    loadSystemMenu()
                }
            }
        }
    }

    /**
     * 加载系统菜单
     */
    override fun loadSystemMenu() {
        OperationManager.getInstancce().getSystemAllMenus(0, object : OperateListener {
            override fun onSuccess(state: Int, obj: Any?) {
                if(obj != null) {
                    mView!!.loadMenuSuccessed(obj as ArrayList<GetSystemMenuResponse>)
                }
            }

            override fun onFail(code: Int, message: String) {
                mHandler.sendEmptyMessageDelayed(WHAT_LOAD_SYSTEM_MENU, 5000)
                mView!!.loadMenuFailed(code, message)
            }

        })
    }

    fun loadSystemMenu(parentId: Int) {
        OperationManager.getInstancce().getSystemAllMenus(parentId, object: OperateListener{
            override fun onSuccess(state: Int, obj: Any?) {
                TODO("Not yet implemented")
            }

            override fun onFail(code: Int, message: String) {
                TODO("Not yet implemented")
            }

        })
    }

    override fun onDismiss() {
        super.onDismiss()

        mHandler.removeMessages(WHAT_LOAD_SYSTEM_MENU)
    }
    override fun getAppNewlyVersion() {
        if (getAppNewlyVersionIsBusying) return
        getAppNewlyVersionIsBusying = true
        OperationManager.getInstancce().getAppNewlyVersion(object: OperateListener {
            override fun onSuccess(state: Int, obj: Any?) {
                getAppNewlyVersionIsBusying = false
                if(obj != null) {
                    val versionInfo = obj as GetAppNewlyVersionResponse

                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                        mContext.packageManager.getPackageInfo(mContext.packageName, 0).versionCode
                    } else {
                        mContext.packageManager.getPackageInfo(mContext.packageName, 0).longVersionCode
                    }

                    L.d(">>>", "${versionInfo.versioncode}   ${getVersionCode()}")
                    if(versionInfo.versioncode > getVersionCode().toLong()) {
                        mView?.getAppNewlyVersionTrue(versionInfo)
                    } else {
                        mView?.getAppNewlyVersionFalse()
                    }
                }

            }

            override fun onFail(code: Int, message: String) {
                getAppNewlyVersionIsBusying = false
                mView?.getAppNewlyVersionFailed(code, message)
            }

        })
    }

    override fun downloadFile(url: String, savePath: String) {
        if (downloadFileIsBusying) return
        downloadFileIsBusying = true
        OperationManager.getInstancce().downloadFile(url, savePath, object: OperateListener {
            override fun onSuccess(state: Int, obj: Any?) {
                downloadFileIsBusying = false
                L.v(">>>>>>", "MyApplication>>onNewlyVersion>>onSuccess:: obj = ${Gson().toJson(obj)}")

                var data = obj as DownloadFileProgress

                mView?.downloadFileSuccessed(data, savePath)
            }

            override fun onFail(code: Int, message: String) {
                downloadFileIsBusying = false
                L.v(">>>>>>", "MyApplication>>onNewlyVersion>>onFail")
                mView?.downloadFileFailed(message)
            }

        })
    }

    override fun openInstallPage(apkPath: String) {

    }
    /**
     * 获取当前版本号
     */
    private fun getVersionCode(): Int {
        try {
            val packageManager = mContext.packageManager
            val packageInfo = packageManager.getPackageInfo(mContext.packageName, 0)
            return packageInfo.versionCode
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }
}